from fastapi import Request, status
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware

from app.models.account_models import Account


class AuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        path = request.url.path
        account_id = request.cookies.get("id")

        # TODO: this check for debug, remove before production
        if path.startswith("/docs") or path == "/openapi.json":
            response = await call_next(request)
            return response

        if path.startswith("/login"):
            response = await call_next(request)
            return response

        if path.startswith("/registration"):
            if account_id is not None:
                return JSONResponse(
                    status_code=status.HTTP_403_FORBIDDEN, content="FORBIDDEN"
                )
            else:
                response = await call_next(request)
                return response

        if account_id is None:
            return JSONResponse(
                status_code=status.HTTP_401_UNAUTHORIZED, content="UNAUTHORIZED"
            )

        account = await Account.get_or_none(id=int(account_id))

        if request.method == "DELETE" or request.method == "PUT":
            if path.startswith("/accounts"):
                account_id_path = int(request.url.path.split("/")[-1])
                if account_id_path != int(account_id) or account is None:
                    return JSONResponse(
                        status_code=status.HTTP_403_FORBIDDEN, content="FORBIDDEN"
                    )

        if account is None:
            return JSONResponse(
                status_code=status.HTTP_401_UNAUTHORIZED, content="UNAUTHORIZED"
            )

        response = await call_next(request)
        return response
